package com.zhoug.zmui3.input;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.zhoug.common3.adapters.recycler.layoutmanager.FlowLayoutManager;
import com.zhoug.common3.adapters.recycler2.BaseRecyclerViewAdapter;
import com.zhoug.common3.adapters.recycler2.BaseViewHolder;
import com.zhoug.common3.interfaces.NameTransformer;
import com.zhoug.common3.interfaces.OnRemoveListener;
import com.zhoug.common3.utils.CollectionUtils;
import com.zhoug.common3.utils.MotionEventUtils;
import com.zhoug.common3.utils.TextUtils;
import com.zhoug.zmui3.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.AttrRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 键值对选择器
 *
 * @Author: zhoug
 * @Date: 2024-07-10
 * @Description:
 */
public class ZMUIInputSelector extends ZMUIInputView {
    protected final float minDistance;

    /**
     * 显示选择内容的列表
     */
    protected RecyclerView mRecyclerView;
    /**
     * 数据适配器
     */
    protected ItemAdapter mItemAdapter;
    /**
     * 显示列表窗口回调
     */
    protected OnPopupListener mOnPopupListener;
    /**
     * 移除选择时回调
     */
    protected OnRemoveListener<NameTransformer> mOnRemoveListener;
    /**
     * 是否支持多选
     */
    protected boolean multiSelect = false;
    /**
     * 提示文本
     */
    protected HintText hintText;
    /**
     * value文字大小
     */
    protected float valueSize;
    /**
     * value文字颜色
     */
    protected int valueColor;
    /**
     * 提示文本颜色
     */
    protected int valueHintColor;
    /**
     * value文字样式
     */
    protected int valueStyle;
    /**
     * 设置每个item maxLines
     */
    protected int valueMaxLines;
    /**
     * 以分割线的模式显示选择的值 eg: 北京,上海,南宁
     */
    protected boolean mTextSplitMode;
    /**
     * 分割线
     */
    protected String mSeparator=",";


    public ZMUIInputSelector(Context context) {
        this(context, null);

    }

    public ZMUIInputSelector(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, R.attr.zmui_style_ZMUIInputSelector);
    }

    public ZMUIInputSelector(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        minDistance = MotionEventUtils.getScaledTouchSlop(context);
        init(context, attrs, defStyleAttr);
    }

    @SuppressLint("ClickableViewAccessibility")
    protected void init(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ZMUIInputSelector, defStyleAttr, R.style.zmui_style_ZMUIInputSelector);
        String valueHint = a.getString(R.styleable.ZMUIInputSelector_zmui_valueHint);

        valueSize = a.getDimension(R.styleable.ZMUIInputSelector_zmui_valueSize, 0);
        valueColor = a.getColor(R.styleable.ZMUIInputSelector_zmui_valueColor, 0);
        valueHintColor = a.getColor(R.styleable.ZMUIInputSelector_zmui_valueHintColor, 0);
        valueStyle = a.getInt(R.styleable.ZMUIInputSelector_zmui_valueStyle, Typeface.NORMAL);
        valueMaxLines = a.getInt(R.styleable.ZMUIInputSelector_zmui_valueMaxLines, 0);
        multiSelect = a.getBoolean(R.styleable.ZMUIInputSelector_zmui_multiSelect, false);
        mTextSplitMode=a.getBoolean(R.styleable.ZMUIInputSelector_zmui_textSplitMode, false);
        String separator=a.getString(R.styleable.ZMUIInputSelector_zmui_separator);


        a.recycle();
       setSeparator(separator);
        setHintText(valueHint);
        mInputValueContainer.setClickable(true);
        mInputValueContainer.setFocusable(true);
        mInputValueContainer.setFocusableInTouchMode(true);
        mInputValueContainer.setOnFocusChangeListener(this);
        mInputValueContainer.setOnClickListener(v -> exeOnClick());
        mItemAdapter = new ItemAdapter(getContext());
        mItemAdapter.setData(new ArrayList<>());
        mRecyclerView.setAdapter(mItemAdapter);
        RecyclerView.LayoutManager layoutManager = new FlowLayoutManager(true);
        mRecyclerView.setLayoutManager(layoutManager);
//        mRecyclerView.addItemDecoration(new SpacesItemDecoration(getContext(),5));
        //解决RecyclerView拦截了父容器的单击事件的问题
        mRecyclerView.setOnTouchListener(new OnTouchListener() {
            private float startX;
            private float startY;
            private long startTime;
            private boolean isMove;
            private static final long CLICK_TIME=500;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        startX = event.getX();
                        startY = event.getY();
                        startTime = System.currentTimeMillis();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if(!isMove){
                            if(Math.abs(startX-event.getX())>minDistance || Math.abs(startY-event.getY())>minDistance){
                                isMove=true;
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if(!isMove && System.currentTimeMillis()-startTime<CLICK_TIME){
                            exeOnClick();
                        }
                        startX = 0;
                        startY = 0;
                        startTime = 0;
                        isMove=false;
                        return true;
                }
                return false;
            }
        });
    }

    /**
     * 布局管理器
     *
     * @param layoutManager
     */
    public void setLayoutManager(RecyclerView.LayoutManager layoutManager) {
        if (mRecyclerView != null) {
            mRecyclerView.setLayoutManager(layoutManager);
        }
    }

    /**
     * 设置提示文本
     *
     * @param hintText
     */
    public void setHintText(String hintText) {
        if (hintText != null && !hintText.isEmpty()) {
            this.hintText = new HintText(hintText);
        } else {
            this.hintText = null;
        }
    }

    /**
     * 设置多选
     *
     * @param multiSelect
     */
    public void setMultiSelect(boolean multiSelect) {
        this.multiSelect = multiSelect;
        if (mClearImageView.getVisibility() == VISIBLE) {
            mClearImageView.setVisibility(GONE);
        }
    }

    public boolean isMultiSelect() {
        return multiSelect;
    }


    public void setTextSplitMode(boolean textSplitMode) {
        this.mTextSplitMode = textSplitMode;
        notifyData();
    }

    public void setSeparator(String separator) {
        if(separator!=null){
            this.mSeparator = separator;
        }else {
            this.mSeparator=",";
        }
    }

    /**
     * 设置选择的数据
     *
     * @param select
     * @param <T>
     */
    public <T extends NameTransformer> void setSelect(List<T> select) {
        if (select != null && !select.isEmpty()) {
            mItemAdapter.setData(new ArrayList<>(select));
        } else {
            mItemAdapter.setData(new ArrayList<>());
        }
        notifyData();
        setClearImageState();
    }

    /**
     * 设置选择的数据
     *
     * @param select
     * @param <T>
     */
    public <T extends NameTransformer> void setSingleSelect(T select) {
        if (select != null) {
            mItemAdapter.setData(Arrays.asList(select));
        } else {
            mItemAdapter.setData(new ArrayList<>());
        }
        notifyData();
        setClearImageState();
    }

    /**
     * 获取选择的数据
     *
     * @return
     */
    public List<NameTransformer> getSelect() {
        return mItemAdapter.getData();
    }

    protected void exeOnClick() {
        if (mOnPopupListener != null && isEnabled()) {
            requestValueFocus();
            setExpandIconState(true);
            mOnPopupListener.onClick(self());
        }
    }


    protected void requestValueFocus() {
        if (!mInputValueContainer.hasFocus()) {
            mInputValueContainer.requestFocus();
        }
    }

    public void setExpandIconState(boolean expand) {
        if (mRightImageView != null) {
            mRightImageView.setSelected(expand);
        }
    }


    public void notifyData(){
        if (mItemAdapter != null) {
            mItemAdapter.notifyDataSetChanged1();
        }
    }
    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        notifyData();
    }

    @Override
    protected View createValueView(ViewGroup parent) {
        if (mRecyclerView == null) {
            mRecyclerView = new RecyclerView(getContext());
            mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
            mRecyclerView.setHorizontalScrollBarEnabled(false);
            mRecyclerView.setVerticalScrollBarEnabled(false);
        }
        return mRecyclerView;
    }


    @Override
    protected void onClearClick(View view) {
        //清除输入
        List<NameTransformer> data = mItemAdapter.getData();
        if (data != null && !data.isEmpty()) {
            NameTransformer removeData = data.get(0);
            setSelect(null);
            if (mOnRemoveListener != null) {
                mOnRemoveListener.onRemove(self(), removeData);
            }
        }
    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        super.onFocusChange(v, hasFocus);
        if (hasFocus) {
            //暂时注销,当点击同时获取焦点会调用2次
//            exeOnClick();
        }
        setClearImageState();
    }

    /**
     * 设置清除按钮状态
     */
    protected void setClearImageState() {
        if (mClearIconEnable && !multiSelect && mItemAdapter != null) {
            //单选
            int dataSize = mItemAdapter.getDataSize();
            if (dataSize > 0 && mHasFocus && isEnabled()) {
                mClearImageView.setVisibility(VISIBLE);
            } else {
                mClearImageView.setVisibility(GONE);
            }
        }
    }

    /**
     * @see #setOnPopupListener(OnPopupListener)
     * @deprecated
     */
    @Deprecated
    @Override
    public void setOnClickListener(@Nullable OnClickListener l) {
        super.setOnClickListener(l);
    }

    public void setOnPopupListener(OnPopupListener onPopupListener) {
        this.mOnPopupListener = onPopupListener;
    }

    public void setOnRemoveListener(OnRemoveListener<NameTransformer> onRemoveListener) {
        this.mOnRemoveListener = onRemoveListener;
    }

    /**
     * 单击监听 显示选择窗口
     */
    public interface OnPopupListener {
        void onClick(ZMUIInputSelector selector);
    }

    protected ZMUIInputSelector self() {
        return this;
    }

    protected class ItemAdapter extends BaseRecyclerViewAdapter<NameTransformer> implements View.OnClickListener {

        public ItemAdapter(Context context) {
            super(context);
            setEmptyViewEnable(false);
            setErrorViewEnable(false);
            setLoadMoreEnable(false);
        }

        @Override
        protected int getLayoutId(int viewType) {
            return R.layout.zmui_input_selector_item;
        }

        @Override
        public int getItemCount() {
            int itemCount = super.getItemCount();
            //没有数据的时候显示Item
            if (itemCount == 0 && hintText != null) {
                itemCount = 1;
            }
            if(mTextSplitMode && itemCount>1){
                itemCount=1;
            }
            return itemCount;
        }

        @NonNull
        @Override
        public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            BaseViewHolder baseViewHolder = super.onCreateViewHolder(parent, viewType);
            TextView selectorText = baseViewHolder.getView(R.id.zmui_selector_text);
            setTextSize(selectorText, valueSize);
            setTextColor(selectorText, valueColor);
            setHintTextColor(selectorText, valueHintColor);
            setTypeface(selectorText, valueStyle);
            TextUtils.setMaxLines(selectorText, valueMaxLines);
            return baseViewHolder;
        }

        @Override
        protected void onBindData(BaseViewHolder holder, NameTransformer data, int position, int viewType) {
            TextView selectorText = holder.getView(R.id.zmui_selector_text);
            ImageView selectorClear = holder.getView(R.id.zmui_selector_clear);
            if (data != null) {
                if(mTextSplitMode){
                    //以分割线的模式显示选择的值 eg: 北京,上海,南宁
                    selectorText.setText(CollectionUtils.listToNames(getData(),mSeparator));
                    selectorClear.setVisibility(GONE);
                    holder.itemView.setSelected(false);
                }else{
                    selectorText.setText(data.transformName());
                    //用选中状态表示多选
                    if (multiSelect) {
                        holder.itemView.setSelected(true);
                        if (isEnabled()) {
                            selectorClear.setVisibility(VISIBLE);
                        } else {
                            selectorClear.setVisibility(GONE);
                        }
                    } else {
                        holder.itemView.setSelected(false);
                        selectorClear.setVisibility(GONE);
                    }
                    selectorClear.setClickable(true);
                    selectorClear.setTag(position);
                    selectorClear.setOnClickListener(this);
                }

            } else {
                //提示文本
                if (hintText != null) {
                    selectorText.setHint(hintText.getHintText());
                    holder.itemView.setSelected(false);
                    selectorClear.setVisibility(GONE);
                }

            }
            holder.itemView.setClickable(true);
            holder.itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            requestValueFocus();
            int id = v.getId();
            if (id == R.id.zmui_selector_clear) {
                int pos = (int) v.getTag();
                NameTransformer itemData = getItemData(pos);
                getData().remove(itemData);
                notifyItemRemoved(pos);
                notifyItemRangeChanged(pos, getItemCount());
                if (mOnRemoveListener != null) {
                    mOnRemoveListener.onRemove(self(), itemData);
                }
            } else {
                exeOnClick();
            }
        }
    }

    /**
     * 提示文本
     */
    protected static class HintText implements NameTransformer {
        private String hintText;

        public HintText(String hintText) {
            this.hintText = hintText;
        }

        public String getHintText() {
            return hintText;
        }

        @Override
        public String transformName() {
            return hintText;
        }
    }


}
